package multimedia;

import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Displayable;

import midlet.VadeMecumMIDlet;
import ui.CreateNoteForm;
import ui.RecordAudioForm;
import ui.VadeMecumImageViewer;
import ui.VadeMecumVideoViewer;

public class SaveSnapshotThread implements Runnable {

	private VadeMecumMIDlet midlet;
	
	private byte[] fileByteArray;
	
	private Alert alert;
	
	private Displayable previous;
	
	private long fileId;

	private String fileExtension;
	
	public SaveSnapshotThread(VadeMecumMIDlet midlet, VadeMecumImageViewer previous, byte[] picture, long fileId) {
		this.midlet = midlet;
		this.fileByteArray = picture;
		this.previous = previous;
		this.fileId = fileId;
		this.fileExtension = ".jpg";
		alert = new Alert("", "Picture saved!", null, AlertType.INFO);
		alert.setTimeout(1500);
	}
	
	public SaveSnapshotThread(VadeMecumMIDlet midlet, VadeMecumVideoViewer previous, byte[] videoArray,	long fileId) {
		this.midlet = midlet;
		this.fileByteArray = videoArray;
		this.previous = previous;
		this.fileId = fileId;
		this.fileExtension = ".mpg";
		alert = new Alert("", "Video saved!", null, AlertType.INFO);
		alert.setTimeout(1500);
	}

	public SaveSnapshotThread(VadeMecumMIDlet midlet, RecordAudioForm previous, byte[] audioArray, long fileId) {
		this.midlet = midlet;
		this.fileByteArray = audioArray;
		this.previous = previous;
		this.fileId = fileId;
		this.fileExtension = ".wav";
		alert = new Alert("", "Audio saved!", null, AlertType.INFO);
		alert.setTimeout(1500);
	}

	public SaveSnapshotThread(VadeMecumMIDlet midlet, CreateNoteForm previous, byte[] noteBytes, long fileId) {
		this.fileByteArray = noteBytes;
		this.previous = previous;
		this.fileId = fileId;
		this.fileExtension = ".txt";
		alert = new Alert("", "Note saved!", null, AlertType.INFO);
		alert.setTimeout(1500);
	}

	public void run() {
		System.out.println("vai salvar");
		try { 
//			String url = "file:///e:/Images/vm_file" + fileId + fileExtension;
			String url = "file:///root1/photos/vm_file" + fileId + fileExtension;
			
			FileConnection fconn = (FileConnection)Connector.open(url, Connector.READ_WRITE);  
			if (!fconn.exists()) {  
				fconn.create();  
			}  
			OutputStream ops = fconn.openOutputStream();  
			ops.write(fileByteArray);  
			ops.close();  
			fconn.close();  
			midlet.display.setCurrent(alert, previous);
		} catch (IOException ioe) {  
			midlet.error(ioe);
		} catch (SecurityException se) {
			midlet.error(se);  
		} catch (Exception e) {
			midlet.error(e);
		}
	}

}
